import { Context } from 'koa';
import { queryOne, query } from '../database/mysql';
import { User } from '../database/models';
import { comparePassword } from '../utils/password';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';
import { generateToken, setTokenToRedis, removeToken, addTokenToBlacklist, verifyToken } from '../middleware/auth';
import { verifyCaptcha, generateCaptcha } from '../utils/captcha';

/**
 * 生成验证码
 */
export async function getCaptcha(ctx: Context): Promise<void> {
  try {
    const { id, svg } = await generateCaptcha();
    
    // 设置响应头，返回SVG图片
    ctx.set('Content-Type', 'image/svg+xml');
    ctx.set('Cache-Control', 'no-cache, no-store, must-revalidate');
    ctx.set('Pragma', 'no-cache');
    ctx.set('Expires', '0');
    
    // 返回验证码ID和SVG
    success(ctx, {
      id,
      svg,
    });
  } catch (err: any) {
    error(ctx, ResponseCode.INTERNAL_SERVER_ERROR, `生成验证码失败: ${err.message}`);
  }
}

/**
 * 登录
 */
export async function login(ctx: Context): Promise<void> {
  const { username, password, captchaId, captcha } = ctx.request.body as {
    username?: string;
    password?: string;
    captchaId?: string;
    captcha?: string;
  };

  if (!username || !password) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户名和密码不能为空');
    return;
  }

  // 验证验证码
  if (!captchaId || !captcha) {
    error(ctx, ResponseCode.BAD_REQUEST, '验证码不能为空');
    return;
  }

  const isCaptchaValid = await verifyCaptcha(captchaId, captcha);
  if (!isCaptchaValid) {
    error(ctx, ResponseCode.BAD_REQUEST, '验证码错误或已过期');
    return;
  }

  const user = await queryOne<User>('SELECT * FROM users WHERE username = ? AND status = 1', [username]);
  if (!user) {
    error(ctx, ResponseCode.USER_NOT_FOUND);
    return;
  }

  const isPasswordValid = await comparePassword(password, user.password);
  if (!isPasswordValid) {
    error(ctx, ResponseCode.INVALID_PASSWORD);
    return;
  }

  // 生成Token
  const token = generateToken({
    userId: user.id,
    username: user.username,
    isAdmin: user.is_admin,
  });

  // 存储Token到Redis
  await setTokenToRedis(user.id, token);

  // 返回用户信息和Token
  const { password: _, ...userInfo } = user;
  success(ctx, {
    user: userInfo,
    token,
  });
}

/**
 * 登出
 */
export async function logout(ctx: Context): Promise<void> {
  const user = ctx.state.user as User;
  const body = ctx.request.body as { token?: string } | undefined;
  const token = ctx.get('Authorization')?.replace('Bearer ', '') || body?.token;

  if (user) {
    await removeToken(user.id);
  }

  if (token) {
    const payload = verifyToken(token);
    if (payload) {
      // 将Token加入黑名单
      const expiresIn = 7 * 24 * 60 * 60; // 7天
      await addTokenToBlacklist(token, expiresIn);
    }
  }

  success(ctx, { message: '登出成功' });
}

/**
 * 获取当前用户信息
 */
export async function getCurrentUser(ctx: Context): Promise<void> {
  const user = ctx.state.user as User;
  
  if (!user) {
    error(ctx, ResponseCode.UNAUTHORIZED);
    return;
  }

  // 获取用户权限
  const permissions = await query(
    `SELECT p.* FROM permissions p
     INNER JOIN user_permissions up ON p.id = up.permission_id
     WHERE up.user_id = ?`,
    [user.id]
  );

  const { password: _, ...userInfo } = user;
  success(ctx, {
    ...userInfo,
    permissions,
  });
}

